using Distributed

const jobs = Channel{Int}(32);
const results = Channel{Tuple}(32);

function do_work()                     # 消费者
    for job_id in jobs                   # 用for循环从输入通道jobs中读取任务数据
        exec_time = rand()
        sleep(exec_time)               # 用sleep模拟处理过程
        put!(results, (job_id, exec_time))  # 将结果放入输出通道results中
    end
end

function make_jobs(n)                  # 生产者
    for i in 1:n                        
        put!(jobs, i)                   # 往任务通道jobs中放入数据
    end
end

n = 12;

@async make_jobs(n); 			    # 将生产者加入任务调度中

for i in 1:4                           
    @async do_work()               # 异步地启动4个消费者，实现并行消费
end

@elapsed while n > 0                   # 打印消费者执行后的结果
            job_id, exec_time = take!(results);    # 从结果通道中提取数据
            println("$job_id finished in $(round(exec_time,digits=2)) seconds")
            global n = n - 1
        end
